package com.xiaoxiaoniu.airoleplay.services;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Service
public class AIService {

    @Value("${qiniu.ai.deepseek-url}")
    private String deepSeekUrl;

    @Value("${qiniu.ai.token}")
    private String apiToken;

    @Value("${qiniu.ai.timeout:30000}")
    private int timeout;

    @Autowired
    private WebClient.Builder webClientBuilder;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RoleSkillService roleSkillService;

    // 角色预设提示词
    private static final Map<String, String> ROLE_PROMPTS = new HashMap<>();

    static {
        ROLE_PROMPTS.put("哈利波特", "你现在是哈利·波特，霍格沃茨魔法学校的学生。你说话要带有魔法世界的特色，可以使用魔法咒语和魔法世界的术语。你勇敢、善良，总是愿意帮助朋友。请用中文回复，保持角色特点。");
        ROLE_PROMPTS.put("苏格拉底", "你现在是古希腊哲学家苏格拉底。你擅长使用问答法（苏格拉底反诘法）来引导思考。你说话要充满智慧，喜欢提问而不是直接给出答案。请用中文回复，保持哲学家的思考方式。");
        ROLE_PROMPTS.put("福尔摩斯", "你现在是夏洛克·福尔摩斯，世界著名的侦探。你观察力极其敏锐，擅长逻辑推理。你说话要冷静、理性，经常能从细节中推断出重要信息。请用中文回复，展现侦探的推理能力。");
        ROLE_PROMPTS.put("爱因斯坦", "你现在是物理学家阿尔伯特·爱因斯坦。你充满智慧，善于用简单的比喻解释复杂的物理概念。你幽默、谦逊，对世界充满好奇心。请用中文回复，体现科学家的思考方式。");
    }
    
    /**
     * 获取备用回复
     * @param role 角色名
     * @param userMessage 用户消息
     * @return 备用回复内容
     */
    public String getFallbackResponse(String role, String userMessage) {
        return roleSkillService.getIntelligentFallback(role, userMessage);
    }

    public CompletableFuture<String> getAIResponse(String role, String userMessage) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println("=== 开始调用七牛云AI API ===");
                System.out.println("API端点: " + deepSeekUrl);
                System.out.println("使用模型: deepseek-v3");

                // 构建符合七牛云API格式的请求
                Map<String, Object> requestBody = buildRequestBody(role, userMessage);
                System.out.println("请求体: " + objectMapper.writeValueAsString(requestBody));

                // 发送请求
                String response = webClientBuilder.build()
                        .post()
                        .uri(deepSeekUrl)
                        .header(HttpHeaders.AUTHORIZATION, "Bearer " + apiToken)
                        .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                        .bodyValue(requestBody)
                        .retrieve()
                        .onStatus(status -> status.isError(), clientResponse -> {
                            System.err.println("HTTP错误状态: " + clientResponse.statusCode());
                            return clientResponse.bodyToMono(String.class)
                                    .flatMap(errorBody -> {
                                        System.err.println("错误响应体: " + errorBody);
                                        return Mono.error(new RuntimeException("HTTP " + clientResponse.statusCode() + ": " + errorBody));
                                    });
                        })
                        .bodyToMono(String.class)
                        .block();

                System.out.println("API响应: " + response);

                // 解析响应
                return parseAIResponse(response);

            } catch (Exception e) {
                System.err.println("AI服务调用失败: " + e.getMessage());
                e.printStackTrace();
                // 使用智能备用回复
                return roleSkillService.getIntelligentFallback(role, userMessage);
            }
        });
    }

    private Map<String, Object> buildRequestBody(String role, String userMessage) {
        Map<String, Object> requestBody = new HashMap<>();

        // 使用官方文档推荐的模型
        requestBody.put("model", "deepseek-v3");

        // 构建消息列表 - 严格按照官方格式
        List<Map<String, String>> messages = new ArrayList<>();

        // 系统提示词
        String systemPrompt = ROLE_PROMPTS.getOrDefault(role,
                "你是一个有趣的对话伙伴，请用生动有趣的方式与用户交流。请用中文回复。");

        Map<String, String> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");
        systemMessage.put("content", systemPrompt);
        messages.add(systemMessage);

        // 用户消息
        Map<String, String> userMessageMap = new HashMap<>();
        userMessageMap.put("role", "user");
        userMessageMap.put("content", userMessage);
        messages.add(userMessageMap);

        requestBody.put("messages", messages);
        requestBody.put("stream", false);
        requestBody.put("max_tokens", 1000);
        requestBody.put("temperature", 0.7);

        return requestBody;
    }

    private String parseAIResponse(String response) throws Exception {
        if (response == null || response.trim().isEmpty()) {
            throw new RuntimeException("AI响应为空");
        }

        JsonNode rootNode = objectMapper.readTree(response);

        // 调试：打印完整的响应结构
        System.out.println("响应结构: " + rootNode.toPrettyString());

        // 检查错误
        if (rootNode.has("error")) {
            String errorMsg = rootNode.get("error").get("message").asText();
            throw new RuntimeException("AI API返回错误: " + errorMsg);
        }

        // 解析回复内容 - 兼容多种响应格式
        if (rootNode.has("choices") && rootNode.get("choices").size() > 0) {
            JsonNode choice = rootNode.get("choices").get(0);
            if (choice.has("message") && choice.get("message").has("content")) {
                return choice.get("message").get("content").asText();
            } else if (choice.has("text")) {
                return choice.get("text").asText();
            }
        }

        // 如果以上都不匹配，尝试直接获取消息内容
        if (rootNode.has("message") && rootNode.get("message").has("content")) {
            return rootNode.get("message").get("content").asText();
        }

        throw new RuntimeException("无法解析AI响应格式: " + response);
    }

    // 测试API连通性的方法
    public CompletableFuture<Boolean> testAPIConnection() {
        return CompletableFuture.supplyAsync(() -> {
            try {
                // 发送一个简单的测试请求
                Map<String, Object> testRequest = new HashMap<>();
                testRequest.put("model", "deepseek-v3");

                List<Map<String, String>> messages = new ArrayList<>();
                Map<String, String> testMessage = new HashMap<>();
                testMessage.put("role", "user");
                testMessage.put("content", "简单回复'你好'即可");
                messages.add(testMessage);

                testRequest.put("messages", messages);
                testRequest.put("max_tokens", 10);
                testRequest.put("stream", false);

                String response = webClientBuilder.build()
                        .post()
                        .uri(deepSeekUrl)
                        .header(HttpHeaders.AUTHORIZATION, "Bearer " + apiToken)
                        .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                        .bodyValue(testRequest)
                        .retrieve()
                        .bodyToMono(String.class)
                        .timeout(java.time.Duration.ofSeconds(10))
                        .block();

                return response != null && response.contains("choices");

            } catch (Exception e) {
                System.err.println("API连通性测试失败: " + e.getMessage());
                return false;
            }
        });
    }
}